const { exec } = require("../db/mysql");

const addClass = (classData) => {
  let data = classData.data;
  let arr = [];
  for (let i = 0; i < data.length; i++) {
    let temp = [];
    temp = temp.concat(data[i].class_name);
    temp = temp.concat(data[i].class_num);
    arr = arr.concat([temp]);
  }
  const sql = `insert into class(class_name,class_num) values ?`;

  return exec(sql, arr).then((insertData) => {
    if (insertData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};
const addOClass = (classData = {}) => {
  const class_name = classData.class_name
  const class_num = classData.class_num;
  const sql = `insert into class (class_name,class_num) 
    values('${class_name}','${class_num}');`;

  return exec(sql).then((insertData) => {
    if (insertData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};
const getClassList = () => {
  const sql = `select * from class`;
  return exec(sql);
};
const delClass = (id) => {
  const sql = `delete from class where class_id=${id}`;
  return exec(sql).then((delData) => {
    if (delData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};
const delSomeClass = (classData = {}) => {
  let arr = classData.arr;
  let len = arr.length;
  let sql = `delete from class where class_id in (`;
  for (let i = 0; i < len - 1; i++) {
    sql += arr[i] + `,`;
  }
  sql += arr[len - 1] + `)`;

  return exec(sql).then((delData) => {
    if (delData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};
const updateClass = (id, classData = {}) => {
  let class_name = classData.class_name;
  let class_num = classData.class_num;

  const sql = `update class set class_name='${class_name}',class_num='${class_num}' where class_id=${id}`;
  return exec(sql).then((updateData) => {
    if (updateData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};

module.exports = {
  addClass,
  addOClass,
  getClassList,
  delClass,
  delSomeClass,
  updateClass,
};
